<?php
/**
 * 获取服务器公钥接口
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// 处理预检请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// 只允许GET请求
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

// 获取公钥
$public_key = get_public_key();
if (!$public_key) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Failed to get public key']);
    exit;
}

echo json_encode([
    'success' => true,
    'public_key' => $public_key,
    'timestamp' => time()
]);

/**
 * 获取公钥
 */
function get_public_key() {
    $key_file = __DIR__ . '/keys/public_key.pem';
    if (!file_exists($key_file)) {
        return false;
    }
    return file_get_contents($key_file);
}
?>
